package com.example.qihuibao.widget.view

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

/**
 *     author : cwwei
 *     e-mail : 494545699@qq.com
 *     date   : 2022/08/13
 *     desc   :
 */
class CommonRecyclerView(context: Context, attrs: AttributeSet?) : RecyclerView(context, attrs) {
    private var layoutId = 0
    private var data:List<Any>? = null
    //    private var count = 0
    private var onBinViewHolder:((itemView: View, pos:Int)->Unit)? = null
    private var onItemClick:((pos:Int)->Unit)? = null
    private var onItemLongClick:((pos:Int)->Unit)? = null
    private var onItemOffsets:((outRect: Rect, itemPosition: Int, rv:RecyclerView)->Unit)? = null

    fun init(itemLayoutId:Int, layoutManager:LayoutManager, data:List<Any>?, onBinViewHolder:(itemView: View, pos:Int)->Unit, onItemClick:((pos:Int)->Unit)? = null, onItemLongClick:((pos:Int)->Unit)? = null, onItemOffsets:((outRect: Rect, itemPosition: Int, rv:RecyclerView)->Unit)? = null) {
        post {
            layoutId = itemLayoutId
            this.layoutManager = layoutManager
            this.data = data
            this.onBinViewHolder = onBinViewHolder
            this.onItemClick = onItemClick
            this.onItemLongClick = onItemLongClick
            this.onItemOffsets = onItemOffsets

            addItemDecoration(TItemDecoration())
            this.adapter = Adapter()
        }
    }


    inner class Adapter : RecyclerView.Adapter<ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder(LayoutInflater.from(parent.context).inflate(layoutId, parent, false))
        }

        override fun getItemCount() = data?.size?:0

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            if (onBinViewHolder != null) {
                onBinViewHolder!!(holder.itemView, position)
            }
        }

    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        init {
            itemView.setOnClickListener {
                if (onItemClick != null) {
                    onItemClick!!(layoutPosition)
                }
            }
            itemView.setOnLongClickListener {
                if (onItemLongClick != null) {
                    onItemLongClick!!(layoutPosition)
                }
                false
            }
        }
    }

    inner class TItemDecoration: RecyclerView.ItemDecoration() {
        override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
            if (onItemOffsets != null) {
                onItemOffsets!!(outRect, itemPosition, parent)
            }
        }
    }
}